package com.zjsru.studyplan1;

/**
 * 轮转数组
 * <p>
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 */
public class rotate {
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[(i + k) % n] = nums[i];
        }
        System.arraycopy(arr, 0, nums, 0, n);
        System.out.println(nums);
    }

    /**
     * 反转数组
     *
     * @param nums nums
     * @param k    k
     */
    public void rotate2(int[] nums, int k) {
        k %= nums.length;
        //1,2,3,4,5,6,7 -> 7,6,5,4,3,2,1
        this.helper(nums, 0, nums.length - 1);
        //7,6,5 - 4,3,2,1 -> 5,6,7,4,3,2,1
        this.helper(nums, 0, k - 1);
        //5,6,7-4,3,2,1 -> 5,6,7,1,2,3,4
        this.helper(nums, k, nums.length - 1);
    }

    /**
     * 反转数组助手类
     *
     * @param nums  nums
     * @param start 开始
     * @param end   结束
     */
    public void helper(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }

    public static void main(String[] args) {
        rotate rotate = new rotate();
        int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7};
        int k = 3;
        rotate.rotate(nums, k);
    }
}
